<template lang="pug">
  div
    .pane-header
      .option
        el-button(size="small" round type="success" @click="onAppend") 增加
      el-pagination(background @current-change="handleCurrentChange" :current-page.sync="pageNum" :page-size="per_page" layout="total, prev, pager, next" :total="totalCount")
    el-table(:data='dataList')
      el-table-column(prop='id' label='编号' width='80')
      el-table-column(prop='name' label='用户名' width='380')
      el-table-column(prop='email' label='电子邮件' width='280')
      el-table-column(label='操作')
        template(slot-scope="scope")
          el-button(size="small" @click="rowEditBtn(scope.row,'role')") 角色
          el-button(size="small" @click="rowEditBtn(scope.row,'user')") 编辑
          el-button(size="small" type="danger" @click="rowDeleteBtn(scope.$index, scope.row)") 删除
    el-dialog(:visible.sync='dialogFormVisible' modal=true append-to-body=true close-on-click-moda=false)
      el-tabs(v-model='userTabName')
        el-tab-pane(label='用户管理' name='user')
          el-form(ref='editUserFrom' label-suffix='：' label-position='right' :model='editItem' :rules='rules' label-width='120px')
            el-form-item(prop='name' label='用户名')
              el-col(:span='15')
                el-input(type='text' v-model='editItem.name')
            el-form-item(prop='email' label='电子邮件')
              el-col(:span='15')
                el-input(type='text' v-model='editItem.email')
            el-form-item(prop='password' label='密码')
              el-input(type='text' v-model='editItem.password')
        el-tab-pane(label='赋角色' name='role' :disabled='editItem.id == 0')
          el-form(ref='editUserRoleFrom' label-suffix='：' label-position='right' :model='editItem' label-width='120px')
            el-form-item(prop='roles' label='角色')
              el-col(:span='24')
                el-checkbox-group(v-model='editItem.roles')
                  el-row(:gutter='24')
                    template(v-for='{ id, name} in roleList')
                      el-col(:span='6')
                        el-checkbox(:label='id' :key='id') {{name}}
      .dialog-footer(slot='footer')
        el-button(@click='dialogFormVisible = false') 取 消
        el-button(type='primary' @click="saveBtn('editUserFrom')") 确定
</template>

<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";
import RemoteValidatorMixin from "../../../../components/RemoteValidatorAndTableEditMixin";
import _ from "lodash";
import {
  user_list,
  user_save,
  user_remove,
  user_info,
  role_all,
  user_save_role
} from "../../../../services";

@Component({
  mixins: [RemoteValidatorMixin],
  components: {}
})
export default class UserPane extends Vue {
  public userTabName: string = "user";

  public dialogFormVisible: boolean = false;

  public roleList: any[string] = {};

  public editItem: any = {
    id: 0,
    name: "",
    password: "",
    email: "",
    roles: []
  };

  constructor() {
    super();
    this.dataItem = "editItem";
  }

  public mounted() {
    let self: any = this;
    this.$nextTick(function() {
      this.$on("update", async function() {
        let data: any = await user_list(self.pageNum);
        if (data.success) {
          self.list = data.data;
        }
      });
    });
  }

  public async _getRoleList() {
    let { success, data } = await role_all();
    if (success) {
      this.roleList = data;
    } else {
      this.roleList = {};
    }
  }

  public onAppend() {
    this.editItem = {
      name: "",
      id: 0,
      password: "",
      email: "",
      roles: []
    } as any[string];
    this._getRoleList();
    this.userTabName = 'user';
    this.dialogFormVisible = true;
  }

  public async _getUserEditInfo(id: number) {
    let { success, data } = await user_info(id);
    if (success) {
      console.log(data);
      let editUser:any = _.pick(data,['name','id','email']);
      editUser['roles']=_.map(data.roles, (item)=>item.id);
      this.editItem = editUser;
    }
    return success;
  }

  public async rowEditBtn(data: any, target: string) {
    if (await this._getUserEditInfo(data.id)) {
      this.dialogFormVisible = true;
      this.userTabName = target;
      this._getRoleList();
    }
  }

  public async saveBtn() {
    let self: UserPane = this;
    let formName = "editUserFrom";
    if (this.userTabName === "user") {
      self.remoteValidate(self, formName, user_save).then(
        (data: any) => {
          if (data) {
            self.$message({
              showClose: true,
              message: "保存成功"
            });
            self.updateRowItem(self.list.data, data, "id");
            self.editItem = data;
            self.userTabName = "role";
          }
        },
        function(data: any) {
          console.log("error");
        }
      );
    } else {
      let { success } = await user_save_role(
        this.editItem.id,
        this.editItem.roles
      );
      if (success) {
        self.dialogFormVisible = false;
        this.$message({
          showClose: true,
          message: "修改角色成功"
        });
      }
    }
  }
  public async rowDeleteBtn(idx: number, rowData: any) {
    this.rowRemove(user_remove, rowData.id, this.dataList, idx, "权限");
  }
}
</script>

<style lang="scss" scoped>
.pane-header {
  display: flex;
  margin-top: 1rem;
  justify-content: space-between;
}
</style>

